package com.fh.controller.swagger;


import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.fh.annotation.IgnoreAuth;
import com.fh.controller.assign_out.AssignOutController;
import com.fh.mapper.loan.CallLoanInfoMapper;
import com.fh.model.loan.CallLoanInfoDto;
import com.fh.model.system.User;
import com.fh.service.loantaskimpl.LoanTaskOverServiceImpl;
import com.fh.service.runbatch.IRunBatchService;
import com.fh.util.Const;
import com.fh.util.R;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

@Api(value = "api")
@Controller
@RequestMapping("/api")
public class TestSwagger {

	@Autowired
	private HttpServletResponse response;

	@Autowired
	private HttpServletRequest request;
	
	@Autowired
	private LoanTaskOverServiceImpl loanTaskOverService;
	
	@Autowired
    private CallLoanInfoMapper callLoanInfoMapper;
	
	private Logger loger = LoggerFactory.getLogger(TestSwagger.class);
	@Autowired
	private IRunBatchService service;

	 String QUEUEKEY = "test_queue_key";

	@RequestMapping(value = "/testIgnoreAuth", method = RequestMethod.POST)
	@ResponseBody
	@ApiOperation(value = "测试方法，忽略认证", httpMethod = "POST")
	@IgnoreAuth
	public R testIgnoreAuth(@RequestParam(required = false) String access_token) {
		//loger.error("测试抛出的异常", new RuntimeException());
		return R.ok().put("data", "哈哈");
	}

	@RequestMapping(value = "/testAuth", method = RequestMethod.POST)
	@ResponseBody
	@ApiOperation(value = "测试方法，需要认证", httpMethod = "POST")
	public R testAuth(@RequestParam(required = false) String access_token) {
		
		return R.ok().put("data", "哈哈");
	}

	@RequestMapping(value = "/testExe", method = RequestMethod.POST)
	@ResponseBody
	@ApiOperation(value = "手动跑批", httpMethod = "POST")
	@IgnoreAuth
	public R testExe(@RequestParam(value="count",required=false)Integer count) {
		try {
			//判断权限只有管理员登录才有跑批权限
			Subject currentUser = SecurityUtils.getSubject();  
			Session session = currentUser.getSession();
			User user = (User)session.getAttribute(Const.SESSION_USER);
			if (user != null && user.getUSERNAME().equals("admin")) {
				if (count == null) {
					count = 1;
				}
				service.executeRunBatch(count);
				//跑批成功插入
				service.insertFlag("Y");
				return R.ok("跑批成功!");
			}else{
				return R.error(500, "没有跑批权限!");
			}
		} catch (Exception e) {
			loger.error("跑批异常", e);
			//跑批插入失败
			service.insertFlag("N");
			return R.error(500, "数据异常,跑批失败!");
		}
	}
	
	
	/**
	 * 催收提前还款功能，接口结案改MQ实时结案
	 */
	@RequestMapping(value = "/callLoanOverPaopi", method = RequestMethod.POST)
	@ResponseBody
	@ApiOperation(value = "已结案跑批信息", httpMethod = "POST")
	@IgnoreAuth
	public R saveC(@RequestParam(value="repaymentId",required=true) String repaymentId,
			       @RequestParam(value="acountYet",required=true)BigDecimal notReturnAmount,
			       @RequestParam(value="date 如:2017-12-06",required=true) String date,
			       @RequestParam(value="status:1 内催，2 外催",required=true) int status) {
		
		CallLoanInfoDto callLoanInfoDto = new CallLoanInfoDto();
		callLoanInfoDto.setRepaymentId(repaymentId);
		CallLoanInfoDto callLoanInfo = callLoanInfoMapper.fetchByRepaymentId(callLoanInfoDto);
		String dt2=null;
		DateFormat df2 = new SimpleDateFormat("yyyy-MM-dd");
		Date date1;
		try {
			date1 = df2.parse(date);
			Calendar c2 = Calendar.getInstance();
			c2.setTime(date1);
			dt2 = df2.format(c2.getTime());
		} catch (ParseException e) {
			e.printStackTrace();
		}
		
		if(1==status){//1 内催，2 外催
			status=2;
		}else if(2==status){
			status=4;
		}else{
			status=2;
		}
		int a=-1;
		if(callLoanInfo!=null){
			if(2==callLoanInfo.getStatus()||4==callLoanInfo.getStatus()){
				a=8;
			}else{
				a= loanTaskOverService.updateByEndCase(repaymentId,notReturnAmount,status,callLoanInfo.getVersion(),dt2);
			}
		}
		 if(a==1) {
			 loanTaskOverService.selectCaseOver(repaymentId);//将结案的数据迁移到结案表
			 return R.ok( "成功");
	      }else if(a==8){
	    	   return R.error("已经做过结案操作");
	      }else if(a==-1){
	    	  return R.error("不存在该逾期案件");
	      }else{
	    	  return R.error("失败");
	      }
	}

	@RequestMapping(value = "/overCaseJobExecute", method = RequestMethod.POST)
	@ResponseBody
	@ApiOperation(value = "手动补漏结案", httpMethod = "POST")
	@IgnoreAuth
	public R overCaseJobExecute() {
		try {
			//判断权限只有管理员登录才有跑批权限
			Subject currentUser = SecurityUtils.getSubject();  
			Session session = currentUser.getSession();
			User user = (User)session.getAttribute(Const.SESSION_USER);
			if (user != null && user.getUSERNAME().equals("admin")) {
				int a=loanTaskOverService.overCaseJobExecute();
				
				if(1==a){
					return R.ok("手动补漏结案成功!");
				}else if(a==Const.OVER_CASH){
					return R.ok("··············跑漏数据····已经做过结案操作·················");
				}else if(a==Const.NOT_RETURN_MSG){
					return R.ok("··············跑漏数据····不存在该逾期案件··················");
				}else if(a==Const.THOERS_ERROR){
					return R.ok("··············跑漏数据····其他异常,结案失败·················");
				}else{
					return R.ok("·············跑漏数据····未知异常,结案失败··············");
				}
			}else{
				return R.error(500, "没有手动补漏结案权限!");
			}
		} catch (Exception e) {
			loger.error("手动补漏结案异常", e);
			return R.error(500, "数据异常,手动补漏结案失败!");
		}
	}

}
